<?php

require_once 'libs/P.php';

class GameController extends BaseController
{

    var $user_id;
    var $user_name;
    var $password;

    function init()
    {
        //get user info from sesssion
        $this->_bw_money = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_bw_money')
                ->order('money asc')
                ->queryAll();
        //get userinfo

        $this->user_id = Yii::app()->getSession()->get('user_id', '1');

        $this->user_name = 'Phu';
    }

    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform
                'actions' => array('xacnhan', 'choilode', 'bomb', 'removebomb', 'chat', 'blackorwhite', 'play', 'luckytrain', 'betbw'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex()
    {
        // using the default layout 'protected/views/layouts/main.php'
        $data = array();
        $this->render('index', $data);
    }

    //cat day bomb
    public function actionremovebomb()
    {
        $this->init();
        if (isset($_POST['game_id']) && isset($_POST['string_color']))
        {
            $string_color = $_POST['string_color'];
            $game_id = $_POST['game_id'];
            //get game info
            $gamebomb = array();
            $gamebomb = Yii::app()->db->createCommand()
                    ->select('*')
                    ->from('ld_make_bomb mb')
                    ->join('ld_user u', 'mb.user_id=u.user_id')
                    ->where('status=:stt and id=:game_id', array(':stt' => '0', ':game_id' => $game_id))
                    ->queryRow();

            //user play
            $cur_user = Yii::app()->db->createCommand()
                    ->select('*')
                    ->from('ld_user')
                    ->where('user_id=:id1', array(':id1' => $this->user_id))
                    ->queryRow();

            //check is enoug money
            if ($cur_user['lr_money'] >= $gamebomb['money'])
            {
                if ($gamebomb['string_color'] == $string_color)
                {
                    //win - set lai status game
                    $columns = array();
                    $columns['status'] = 1;
                    $columns['date_end'] = date('Y:m:d H:i:s');;
                    Yii::app()->db->createCommand()->update('ld_make_bomb', $columns, 'id='.$game_id);
                    //add point - subtract point for user
                    //get current userinfo

                    $cur_point_user = $cur_user['lr_money'];
                    $moneygetwin = 0;
                   if($gamebomb['money']>=0.5 && $gamebomb['money']<2)
                   {
                   		$cur_point_user += ($gamebomb['money']-0.05);
                       $moneygetwin = ($gamebomb['money']-0.05);
                   }
                   if($gamebomb['money']>=2 && $gamebomb['money']<5)
                   {
                   		$cur_point_user += ($gamebomb['money']-0.1);
                       $moneygetwin = ($gamebomb['money']-0.1);
                   }
                   if($gamebomb['money']>=5 && $gamebomb['money']<=10)
                   {
                   			$cur_point_user += (($gamebomb['money']*90)/100);
                         $moneygetwin = (($gamebomb['money']*90)/100);
                   }
                   
                   // $cur_point_user += $gamebomb['money'];
                    //update
                    Yii::app()->db->createCommand()->update('ld_user', array('lr_money' => $cur_point_user), 'user_id='.$this->user_id);
                    //ld_remove_bomb
                    $ld_remove_bomb = array();
                    $ld_remove_bomb['make_bomb_id'] = $gamebomb['id'];
                    $ld_remove_bomb['remove_bomb_user_id'] = $this->user_id;
                    $ld_remove_bomb['choosen'] = $string_color;
                    Yii::app()->db->createCommand()->insert('ld_remove_bomb', $ld_remove_bomb);
                    echo '<h3>Chúc mừng bạn đã gỡ được bomb và nhận được '.$moneygetwin.'$</h3>';
                    
                    
                    //insert log
                    $win = array();
                    $win['content'] = '<b>' .$gamebomb['user_name'] . '</b>đã gỡ được bomb của <b>'. $this->user_name.'</b> và nhận được $' . $moneygetwin;
                    $win['status'] = 1;
                    Yii::app()->db->createCommand()->insert('ld_play_logs', $win);
                }
                else
                {
                    //lose - set lai status game
                    $columns = array();
                    $columns['status'] = 1;
                    $columns['date_end'] = date('Y:m:d H:i:s');;
                    Yii::app()->db->createCommand()->update('ld_make_bomb', $columns, 'id='.$game_id);

                    //insert log
                    $win = array();
                    $win['content'] = '<b>' . $this->user_name . '</b>bị nổ banh xác vì bomb của <b>'.$gamebomb['user_name'].'</b> và mất $' . $gamebomb['money'];
                    $win['status'] = 0;
                    Yii::app()->db->createCommand()->insert('ld_play_logs', $win);
                    
                    
                    //tinh diem cho doi thu
                    $cur_point_user = $gamebomb['lr_money'];
                    if($gamebomb['money']>=0.5 && $gamebomb['money']<1.9)
                    {
                    	$cur_point_user += ($gamebomb['money']-0.05) + $gamebomb['money'];
                    }
                    if($gamebomb['money']>=2 && $gamebomb['money']<5)
                    {
                    	$cur_point_user += ($gamebomb['money']-0.1) + $gamebomb['money'];
                    }
                    if($gamebomb['money']>=5 && $gamebomb['money']<10)
                    {
                    	$cur_point_user += (($gamebomb['money']*90)/100) + $gamebomb['money'];
                    }
                     
                    // $cur_point_user += $gamebomb['money'];
                    //update
                    Yii::app()->db->createCommand()->update('ld_user', array('lr_money' => $cur_point_user), 'user_id=' . $gamebomb['user_id']);
                    //tru tien thang dang choi
                    Yii::app()->db->createCommand()->update('ld_user', array('lr_money' => $cur_user['lr_money']-$gamebomb['money']), 'user_id=' . $this->user_id);
                    
                    //ld_remove_bomb
                    $ld_remove_bomb = array();
                    $ld_remove_bomb['make_bomb_id'] = $gamebomb['id'];
                    $ld_remove_bomb['remove_bomb_user_id'] = $this->user_id;
                    $ld_remove_bomb['choosen'] = $string_color;
                    Yii::app()->db->createCommand()->insert('ld_remove_bomb', $ld_remove_bomb);
                    //output error
                    echo '<h3>Bạn đã bị nổ banh xác và mất '.$gamebomb['money'].'$</h3>';
                }
            }
            else
            {
                //khong đủ tiền
                echo '<h3>Bạn không đủ '.$gamebomb['money'].'$ để chơi</h3>';
            }
        }
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionBomb()
    {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        //command
        $this->init();
        $user_id = $this->user_id;

        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'bomb_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;

        
        //dat bomb
        if (isset($_POST['makebomb']) && isset($_POST['day']))
        {
        	//check xem co tien ko da
        	$cuUser = Yii::app()->db->createCommand()
	        			->select('*')
	        			->from('ld_user')
	        			->where('user_id=:uid', array(':uid'=>$this->user_id))
        				->queryRow();
        	//pham vi dat tien 0.5-10
        	if($_POST['bet_money']<0.5 || $_POST['bet_money'] >10)
        	{
        		$data['error'] = 'Số tiền cho phép là 0.5$ - 10$!!!';
        	}else{
        		if($cuUser['lr_money'] < $_POST['bet_money'])
        		{
        			$data['error'] = 'Bạn không đủ tiền để đặt bomb, vui lòng nạp thêm!!!';
        		}else
        		{
        			//insert make bomb table
        			$makebomb = array();
        			$makebomb['user_id'] = $this->user_id;
        			$makebomb['string_color'] = $_POST['day'];
        			$makebomb['status'] = 0;
        			$makebomb['date_start'] = date('Y:m:d H:i:s');
        			$makebomb['money'] = $_POST['bet_money'];
        			//insert
        			Yii::app()->db->createCommand()->insert('ld_make_bomb', $makebomb);
        			$data['success'] = 'Đặt bomb thành công!!!';
        		
        			//tru tien cua no di
        			$user = array();
        			$user['lr_money']  = $cuUser['lr_money'] - $_POST['bet_money'];
        			Yii::app()->db->createCommand()
        			->update('ld_user', $user, 'user_id=' . $this->user_id);
        		}
        	}
        }
        else
        {
        	if (isset($_POST['makebomb']) && (!isset($_POST['string_color']) || !isset($_POST['bet_money'])))
        	{
        		$data['error'] = 'Nhập số tiền và chọn dây!!!';
        	}
        }
        
        //huy bomb
        if(isset($_GET['huy']) && $_GET['huy'] =='yes')
        {
        	$idhuy = $_GET['id'];
        	//set status is huy
        	$huy = array();
        	$huy['status'] = 2;
        	Yii::app()->db->createCommand()
        				->update('ld_make_bomb', $huy, 'user_id=' . $this->user_id . ' and id=' . $idhuy);
        }
        
        //get all bomb cua toi
       /* $mybomb = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_make_bomb mb')
                ->leftJoin('ld_remove_bomb rb', 'rb.make_bomb_id = mb.id')
                ->leftJoin('ld_user u', 'u.user_id = rb.remove_bomb_user_id')
                ->where('mb.user_id=:id', array(':id' => $user_id))
                ->queryAll();*/
        
        $mybomb = Yii::app()->db->createCommand()
			        ->select('*')
			        ->from('ld_remove_bomb rb')
			        ->rightJoin('ld_make_bomb mb', 'rb.make_bomb_id = mb.id')
			        ->leftJoin('ld_user u', 'u.user_id = rb.remove_bomb_user_id')
			        ->where('mb.user_id=:id', array(':id' => $user_id))
			        ->queryAll();
        
        $data['mybomb'] = $mybomb;

        //all bomb toi go
        $mybomb_remove = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_remove_bomb rb')
                ->join('ld_make_bomb mb', 'rb.make_bomb_id = mb.id')
                ->join('ld_user u', 'u.user_id = mb.user_id')
                ->where('rb.remove_bomb_user_id=:id2', array(':id2' => $user_id))
                ->queryAll();
        $data['mybomb_remove'] = $mybomb_remove;

        //get all bomb hien tai
        $allbomb = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_make_bomb mb')
                ->rightJoin('ld_user u', 'mb.user_id=u.user_id')
                ->where('status=:stt and u.user_id<>:uid', array(':stt' => '0', ':uid'=>$this->user_id))
                ->queryAll();
        $data['allbomb'] = $allbomb;

        //play logs data
        $allplaylogs = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_play_logs')
                ->limit(30, 0)
        		->order('id desc')
                ->queryAll();
        $data['play_logs'] = $allplaylogs;
        //chat data
        $data['html_chat'] = $this->getChatData();
        $this->render('bomb', $data);
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        if ($error = Yii::app()->errorHandler->error)
        {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionChat()
    {
        if (isset($_POST['act']) && $_POST['act'] == 'chataction')
        {
            $command = Yii::app()->db->createCommand();
            $data = array();
            $data['user_id'] = $this->user_id;
            $data['comment'] = $_POST['txt'];
            $data['date'] = date("Y-m-d H:i:s");
            //insert database
            $command->insert('ld_chat_bomb', $data);
            //update chat html
            echo $this->getChatData();
        }
    }

    /*
     * Get chat data from ld_chat_bomb
     */

    public function getChatData()
    {
        $chat = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_chat_bomb cb')
                ->join('ld_user u', 'u.user_id=cb.user_id')
                ->order('id desc')
                ->queryAll();

        $html_chat = '';

        foreach ($chat as $c)
        {
            $html_chat .= '<b>- '.$c['user_name'].' </b><i style="font-size:10px;color:red">('.$c['date'].')</i>: '.$c['comment'].'<br/>';
        }
        return $html_chat;
    }

    //game blackorwhite
    public function actionBlackorWhite()
    {
        $this->init();
        $data = array();
        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'blackorwhite_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;
        //asign money
        $data['bw_money'] = $this->_bw_money;
        $this->render('blackorwhite', $data);
    }

    var $_result; //result 
    var $_bw_money; //array of money alow to play

    //http post
    //blackorwhite bet

    public function actionBetbw()
    {
    	$this->init();
    
        //check xem dang nhap chua
        $is_login = true;
        if ($is_login == false)
        {
            echo '<h2>Lỗi</h2><br>Đăng nhập để chơi';
        }
        else
        {
            //check lr of user - can play game with that bet money or not
            $user = Yii::app()->db->createCommand()
            					->select('*')
            					->from('ld_user')
            					->where('user_id=:id and active=:status', array(':id' => $this->user_id, ':status' => '1'))
            					->queryRow();
            //var_dump($user);
            $user_lr = $user['lr_money'];
            $bet_money = $_POST['money'];
            if ($user_lr < $bet_money)
            {
                //can't play
                echo 'lowpoint';
            }
            else
            {
                //can play this game
                //get result from string 1: black 0:white
                //this will be 70 percent can be win
                $listscore_black = explode(' ', '0 0 0 1 0 0 1 0 0 1');
                $listscore_white = explode(' ', '1 1 0 1 1 0 1 1 0 1');

                if (isset($_POST['chose']))
                {
                    //if user chose black
                    if ($_POST['chose'] == 'black')
                    {
                        //user list $listscore_black
                        $random_num_black = rand(0, 9);
                        $this->_result = $listscore_black[$random_num_black];
                    }
                    //if user chose white
                    if ($_POST['chose'] == 'white')
                    {
                        //user list $listscore_black
                        $random_num_white = rand(0, 9);
                        $this->_result = $listscore_white[$random_num_white];
                    }
                }

                //return to user win or lose
                switch ($this->_result)
                {
                    case '1':
                        echo 'black';
                        $this->_result = 'black';
                        break;
                    case '0':
                        echo 'white';
                        $this->_result = 'white';
                    default:
                        ;
                        break;
                }

                //check the result:
                //- win: add lr to user
                //- lose: subtract lr
                //data: - user_id - chose - money - result
                $data['user_id'] = $this->user_id;
                $data['chose'] = $_POST['chose'];
                $data['result'] = $this->_result;
                $data['money'] = $bet_money;
                $data['playdate'] = date("Y-m-d H:i:s");
                $insert_bw_play_logs = Yii::app()->db->createCommand()->insert('ld_bw_logs', $data);

                //check win or lose and save to db
                if ($this->_result == $_POST['chose'])
                {
                    $user_liberty = $user['lr_money'];
                    $user_liberty += $bet_money*1.9;
                }
                if ($this->_result != $_POST['chose'])
                {
                    $user_liberty = $user['lr_money'];
                    $user_liberty -= $bet_money;
                }
                $datauser['lr_money'] = $user_liberty;
                //win or lose - add or subtract point
                Yii::app()->db->createCommand()->update('ld_user', $datauser, 'user_id='.$this->user_id);
            }
        }
    }

    //http post
    //blackorwhite bet
    public function actionPlay()
    {
        if ($_POST['type'] == 'loadinfo')
        {
            echo 'Phu | Nguyen';
        }

        if ($_POST['type'] == 'loadbwhis')
        {
            //show history of this user
            $this->init();
            $hist_play = array();
            $hist_play = Yii::app()->db->createCommand()
                    ->select('*')
                    ->from('ld_bw_logs')
                    ->where('user_id=:id', array(':id' => $this->user_id))
                    ->limit(10, 0)
                    ->order('playdate desc')
                    ->queryAll();

            foreach ($hist_play as $hp)
            {
                if ($hp['chose'] == $hp['result'])
                {
                    echo 'Bạn chọn <b>'.$hp['chose'].'</b> kết quả là <b>'.$hp['result'].'</b> -> bạn nhận được <span style="color:red"><b>'.$hp['money']*1.9.'$</b></span><br/>';
                }
                else
                {
                    if ($hp['chose'] != $hp['result'])
                    {
                        echo 'Bạn chọn <b>'.$hp['chose'].'</b> kết quả là <b>'.$hp['result'].'</b> -> bạn mất <span style="color:red"><b>'.$hp['money'].'$</b></span><br/>';
                    }
                }
            }
        }
    }

    //game luckytrain
    public function actionLuckyTrain()
    {
        $this->init();

        $data = array();
        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'luckytrain_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;
        //load thong tin history
        $lucky_train_next = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_lucky_train lt')
                ->where('lt.status=:id2', array(':id2' => '0'))
                ->queryRow();
        //number user join
        $userjoin = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_lucky_train_logs ltl')
                ->where('ltl.game_id=:gameid2', array(':gameid2' => $lucky_train_next['id']))
                ->order('position asc')
                ->queryAll();
        
        //join
        if (isset($_POST['buyit']))
        {
        	
        	//get current user info
        	$cur_USer = Yii::app()->db->createCommand()
			        	->select('*')
			        	->from('ld_user')
			        	->where('user_id=:uid', array(':uid'=>$this->user_id))
			        	->queryRow();
        	//check xem du tien choi ko
        	if($cur_USer['lr_money']>=1)
        	{
        		//tru tien choi 1$
        		Yii::app()->db->createCommand()->update('ld_user', array('lr_money' => $cur_USer['lr_money']-1), 'user_id='. $this->user_id);
        		//get max player can play
        		$ld_setting = P::getAllRows('ld_setting');
        		$maxpalyer = 0;
        		foreach ($ld_setting as $st)
        		{
        			if ($st['variable'] == 'lucky_train_num_play')
        			{
        				$maxpalyer = $st['value'];
        			}
        		}
        		if (count($userjoin)+1 < $maxpalyer)
        		{
        			//insert to database
        			$user = array();
        			$user['user_id'] = $this->user_id;
        			$user['playdate'] = date('Y:m:d H:i:s');
        			if (count($userjoin) == 0)
        			{
        				$user['position'] = 1;
        			}
        			else
        			{
        				$user['position'] = $userjoin[count($userjoin) - 1]['position'] + 1;
        			}
        			$user['game_id'] = $lucky_train_next['id'];
        			Yii::app()->db->createCommand()->insert('ld_lucky_train_logs', $user);
        		
        			//if is winner - set user_id int ld_lucky_train
        			if ($lucky_train_next['result_num'] == $user['position'])
        			{
        				Yii::app()->db->createCommand()->update('ld_lucky_train', array('user_id' => $this->user_id), 'id='.$lucky_train_next['id']);
        				//cong diem cho user
        		
        				Yii::app()->db->createCommand()->update('ld_user', array('lr_money' => $cur_USer['lr_money']+9), 'user_id='. $this->user_id);
        			}
        		}else
        		{
        			//5 user
        			if(count($userjoin)+1 == $maxpalyer)
        			{
        				//cap nhat user_id thang game
        				Yii::app()->db->createCommand()->update('ld_lucky_train', array('status' => '1', 'enddate'=>date('Y:m:d H:i:s')), 'id='.$lucky_train_next['id']);
        		
        				//create new game
        				//random num next
        				$num_next = rand(1, 10);
        				$random_string = P::generateRandomString(8);
        				$newluckytrain = array();
        				$newluckytrain['result_num'] = $num_next;
        				$newluckytrain['random_string'] = $random_string;
        				$newluckytrain['startdate'] = date('Y:m:d H:i:s');
        				$newluckytrain['status'] = 0;
        		
        				Yii::app()->db->createCommand()->insert('ld_lucky_train', $newluckytrain);
        			}
        		}
        	
        	}else
        	{
        		$data['error'] = 'Bạn không đủ 1$ để chơi, vui lòng nạp thêm';
        	}
        }

        $lucky_train_next = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_lucky_train lt')
                ->where('lt.status=:id2', array(':id2' => '0'))
                ->queryRow();

        //number user join
        $userjoin = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_lucky_train_logs ltl')
                ->where('ltl.game_id=:gameid2', array(':gameid2' => $lucky_train_next['id']))
                ->order('playdate asc')
                ->queryAll();
        $lucky_train_hist = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_lucky_train lt')
                ->join('ld_user u', 'u.user_id = lt.user_id')
                ->where('lt.status=:id2', array(':id2' => '1'))
                ->queryAll();

        $data['lucky_train_hist'] = $lucky_train_hist;
        $data['lucky_train_next'] = $lucky_train_next;
        $data['number_join'] = count($userjoin);
        $this->render('luckytrain', $data);
    }

    public function actionChoiLoDe()
    {
        $now = date('H:i:s d-m-Y');
        $start = date('18:30:00 d-m-Y');
        $end = date('20:00:00 d-m-Y');
        if ($now >= $start && $now <= $end)
        {
            $this->render('khoagame');
            die ();
            return;
        }
        
        $choices = isset($_REQUEST['choices']) ? $_REQUEST['choices'] : array();
        $bet = (isset($_REQUEST['bet']) && is_numeric($_REQUEST['bet'])) ? $_REQUEST['bet'] : 0;
        $gameType = (isset($_REQUEST['type']) && $_REQUEST['type'] !== '') ? $_REQUEST['type'] : 0;

        $isValid = $this->validateGameLoDeInputs($choices, $bet, $gameType);
        if ($isValid)
        {
            $game = LoDeFactory::createGameLoDe($gameType);
            $game->setBet($bet);
            $game->setChoices($choices);
            $user = User::model()->find('user_id = :user_id', array(':user_id' => Yii::app()->user->id));
            $requiredMoney = $game->calculateRequiredAmount();

            if ($requiredMoney > $user->lr_money)
            {
                $depositURL = $this->createAbsoluteUrl('user/deposit');
                Yii::app()->user->setFlash('error', array("Bạn không đủ tiền để chơi. Bạn chỉ còn {$user->lr_money} $. Nhấp vào <a href='$depositURL'>đây</a> để nạp thêm tiền"));
                $this->render('../site/index');
                return;
            }
            $user->lr_money = $user->lr_money - $requiredMoney;
            if ($user->save() && $game->saveDB())
            {
                $this->render('thongbao');
            }
            else
            {
                Yii::app()->user->setFlash('error', array('Có lỗi xảy ra. Xin thử lại'));
                $this->render('../site/index');
            }
        }
        else
        {
            $this->render('../site/index');
        }
    }

    public function actionXacNhan()
    {
        $now = date('H:i:s d-m-Y');
        $start = date('18:30:00 d-m-Y');
        $end = date('20:00:00 d-m-Y');
        if ($now >= $start && $now <= $end)
        {
            $this->render('khoagame');
            return;
        }
        else
        {
            $choices = isset($_REQUEST['choices']) ? $_REQUEST['choices'] : array();
            $bet = (isset($_REQUEST['bet']) && is_numeric($_REQUEST['bet'])) ? $_REQUEST['bet'] : 0;
            $type = (isset($_REQUEST['type']) && $_REQUEST['type'] !== '') ? $_REQUEST['type'] : 0;
            $game = LoDeFactory::createGameLoDe($type);

            $this->render('xacnhan', array('gameName' => $game->getGameName(), 'choices' => $choices, 'bet' => $bet, 'type' => $type));
        }
    }

    private function validateGameLoDeInputs($choices, $bet, $gameType)
    {
        $error = array();

        if ($gameType == 0)
        {
            $error += array('Tham số không hợp lệ');
        }

        if ($bet == 0)
        {
            $error += array('Số tiền cược không hợp lệ');
        }

        if (count($choices) == 0)
        {
            $error += array('Bạn chưa chọn số');
        }

        foreach ($choices as $choice)
        {
            if ($choice === '')
            {
                $error += array('Bạn chọn số không hợp lệ');
            }
        }

        $game = LoDeFactory::createGameLoDe($gameType);
        $game->setBet($bet);
        $game->setChoices($choices);
        if (!$game->validateInputs())
        {
            $error += array('Các số chọn không hợp lệ');
        }
        if (count($error) > 0)
        {
            Yii::app()->user->setFlash('error', $error);
            return FALSE;
        }

        return TRUE;
    }

}